package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.internal.component.DaggerConfirmExhibitionTicketComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.BuyExhibitionTicketFreeModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.ConfirmTicketModel;
import com.zw.yzk.kabu.presenter.ConfirmExhibitionTickPresenter;
import com.zw.yzk.kabu.utils.CalculateUtils;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.utils.WechatPayInfo;
import com.zw.yzk.kabu.view.view.ConfirmExhibitionTickView;

import java.math.BigDecimal;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by zhanwei on 2017/2/5.
 */

public class ConfirmExhibitionTicketActivity extends BaseActivity implements ConfirmExhibitionTickView {

    @Bind(R.id.phone)
    EditText phone;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.type)
    TextView type;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.price)
    TextView price;
    @Bind(R.id.count)
    TextView count;
    @Bind(R.id.total_price)
    TextView totalPrice;
    @Bind(R.id.image)
    ImageView image;

    @Inject
    ConfirmExhibitionTickPresenter presenter;
    private ConfirmTicketModel confirmTicketModel;
    private float total;

    @Override
    public int getLayoutId() {
        return R.layout.activity_confirm_exhibition_ticket;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.confirm_ticket_order))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerConfirmExhibitionTicketComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .buyExhibitionTicketFreeModule(new BuyExhibitionTicketFreeModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        confirmTicketModel = getIntent().getParcelableExtra(ActivityConstant.CONFIRM_EXHIBITION_TICKET_DATA);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkTradeStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void buyTicketSuccess() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 500);
    }

    @Override
    public void queryOrderStateSuccess(String ticketOrderId) {
        ToastManager.getInstance().showToast(this, getResources().getString(R.string.paid_success));
        if(TextUtils.isEmpty(ticketOrderId)) {
            startActivity(new Intent(this, MyTicketActivity.class));
            finish();
        } else {
            Intent intent = new Intent(this, TicketOrderDetailsActivity.class);
            intent.putExtra(ActivityConstant.EXHIBITION_TICKET_ORDER_ID, ticketOrderId);
            startActivity(intent);
            finish();
        }
    }

    @OnClick(R.id.confirm_order)
    public void confirmOrder() {
        if (TextUtils.isEmpty(phone.getText().toString())) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.please_enter_phone));
            return;
        }
        if (confirmTicketModel.getCount() == 0) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.ticket_could_not_be_null));
            return;
        }
        if (total == 0f) {
            buyTicketFree();
            LoadingDialogManager.getInstance().showLoadingDialog(this);
        } else {
            LoadingDialogManager.getInstance().showLoadingDialog(this);
            buyTicket();
        }
    }

    /**
     * 初始化页面展示
     */
    private void init() {

        title.setText(confirmTicketModel.getExhibitionName());
        type.setText(confirmTicketModel.getType());
        time.setText(confirmTicketModel.getExhibitionTime());
        price.setText(ResUtils.formatCurrency(this, confirmTicketModel.getPrice()));
        count.setText(getResources().getString(R.string.goods_count, confirmTicketModel.getCount()));

        total = getTotalPrice(confirmTicketModel.getPrice(), confirmTicketModel.getCount());
        totalPrice.setText(ResUtils.formatCurrency(this, total));

        Glide.with(this)
                .load(confirmTicketModel.getImage())
                .error(R.drawable.im_default)
                .centerCrop()
                .into(image);

        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null) {
            return;
        }
        phone.setText(user.getPhone());
    }

    /**
     * 计算总价
     *
     * @param price 单价
     * @param count 数量
     * @return 总价
     */
    private float getTotalPrice(float price, int count) {
        BigDecimal p = new BigDecimal(price);
        BigDecimal c = new BigDecimal(count);
        BigDecimal total = p.multiply(c);

        return CalculateUtils.setScale(total, 2);
    }

    /**
     * 免费购票
     */
    private void buyTicketFree() {
        presenter.buyTicketFree(confirmTicketModel.getExhibitionId(), confirmTicketModel.getTicketId(), confirmTicketModel.getCount(), phone.getText().toString());
    }

    /**
     * 购买门票
     */
    public void buyTicket() {
        presenter.buyTicket(confirmTicketModel.getExhibitionId(), phone.getText().toString(), confirmTicketModel.getTicketId(), confirmTicketModel.getCount());
    }

    /**
     * 查询订单状态
     */
    public void checkTradeStatus() {
        presenter.checkOrderState();
    }

}
